package com.fantasyland.backend.Service;

import com.fantasyland.backend.Entity.Reply;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReplyService {

    private static final Logger logger = LoggerFactory.getLogger(ReplyService.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private final ObjectMapper objectMapper;

    public ReplyService() {
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule());
    }

    private static final String REPLY_KEY_PREFIX = "replies:";

    /**
     * 获取帖子的所有回复
     */
    public List<Reply> getRepliesByPostId(Long postId) {
        try {
            String key = REPLY_KEY_PREFIX + postId;
            Object repliesData = redisTemplate.opsForValue().get(key);
            
            if (repliesData != null) {
                String jsonString = objectMapper.writeValueAsString(repliesData);
                return objectMapper.readValue(jsonString, new TypeReference<List<Reply>>() {});
            }
            
            return new ArrayList<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 添加新回复
     */
    public Reply addReply(Long postId, String content, String author) {
        logger.info("开始添加回复 - postId: {}, content: {}, author: {}", postId, content, author);
        
        try {
            // 测试Redis连接
            try {
                redisTemplate.getConnectionFactory().getConnection().ping();
                logger.debug("Redis连接正常");
            } catch (Exception e) {
                logger.error("Redis连接失败: {}", e.getMessage());
                throw new RuntimeException("Redis连接失败: " + e.getMessage());
            }
            
            // 获取现有回复
            logger.debug("获取现有回复列表 - postId: {}", postId);
            List<Reply> replies = getRepliesByPostId(postId);
            logger.debug("当前回复数量: {}", replies.size());
            
            // 创建新回复
            Long replyId = System.currentTimeMillis();
            LocalDateTime now = LocalDateTime.now();
            
            logger.debug("创建新回复 - replyId: {}, timestamp: {}", replyId, now);
            Reply newReply = new Reply(replyId, content, author, now, postId);
            
            // 将新回复添加到列表开头（最新的在上方）
            replies.add(0, newReply);
            logger.debug("添加新回复到列表，新的回复数量: {}", replies.size());
            
            // 保存到Redis
            String key = REPLY_KEY_PREFIX + postId;
            logger.debug("保存到Redis - key: {}", key);
            
            redisTemplate.opsForValue().set(key, replies);
            logger.info("成功保存回复到Redis - replyId: {}", replyId);
            
            return newReply;
            
        } catch (Exception e) {
            logger.error("添加回复失败 - postId: {}, error: {}", postId, e.getMessage(), e);
            throw new RuntimeException("添加回复失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取帖子回复数量
     */
    public int getReplyCount(Long postId) {
        List<Reply> replies = getRepliesByPostId(postId);
        return replies.size();
    }

    /**
     * 删除帖子的所有回复
     */
    public void deleteRepliesByPostId(Long postId) {
        String key = REPLY_KEY_PREFIX + postId;
        redisTemplate.delete(key);
    }
}